package com.dq.register;

import com.dq.common.URL;

import java.io.*;
import java.util.*;

/**
 * @ClassName MapRemoteRegister
 * @Description 远程Map服务注册
 * @Author DuX1aoQiang
 * @Date 2023/5/24 19:31
 * @Version 1.0
 */
public class MapRemoteRegister {

    //这个map 由于被Provider  |  Comsumer分开调用 所有map不一样  因此出现 NullPointerException
    private static Map<String, List<URL>> map = new HashMap<>();

    public static void register(String interfaceName, URL url) {
        List<URL> urls = map.get(interfaceName);
        if (urls == null) {
            urls = new ArrayList<>();
        }
        urls.add(url);
        map.put(interfaceName, urls);

        //写入map 保证file 一致
        saveFile();
    }

    public static List<URL> get(String interfaceName) {
        map = readFile();
        return MapRemoteRegister.map.get(interfaceName);
    }


    //todo resolve no same map  => file
    private static void saveFile() {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("map.txt");
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(map);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static Map<String, List<URL>> readFile() {
        try {
            FileInputStream fileInputStream = new FileInputStream("map.txt");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            return (Map<String, List<URL>>) objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

}
